package com.doctor.ui.homedoctor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.doctor.bean.DiseaseRecordBean;
import com.doctor.comm.AlarmReceiver;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.LoadingTip;
import com.doctor.comm.DialogHelper.DialogSelectCallback;
import com.doctor.database.DbOperator;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.R;
import com.doctor.view.DateTimeButton;

public class HealthManagerFrag extends BaseFragment{

	/**
	 * 健康管理
	 */
	
	private Context context;
	private EditText disease,content;
	private TextView searchBtn,remindTime,healthAnaBtn,healthInstructBtn,healthDirectBtn;
	private Calendar calendar;
	private LinearLayout saveBtn,cancelBtn;
	private Click click;
	//存储健康分析、健康指导、健康指示内容
	private String[] content_txt;
	//用来标识按钮，0健康分析，1健康指导，2健康指示
	private int tag;
	private DiseaseRecordBean bean;
	private int id;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		context=getActivity();
		calendar=Calendar.getInstance();
		content_txt=new String[3];
		click=new Click();
		/**
		bean=(DiseaseRecordBean) getArguments().getSerializable(ConstConfig.ID);
		content_txt[0]= bean.getHealthAna() == null ? "" : Html.fromHtml(bean.getHealthAna()).toString();
		content_txt[1]= bean.getHealthInstruct() == null ? "" : Html.fromHtml(bean.getHealthInstruct()).toString();
		content_txt[2]=bean.getHealthDirect() == null ? "" : Html.fromHtml(bean.getHealthDirect()).toString();
		*/
		id = getArguments().getInt(ConstConfig.ID);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		final View view=inflater.inflate(R.layout.health_manager, container, false);
		
		AsyncTask<Integer, Integer, DiseaseRecordBean> task = new AsyncTask<Integer, Integer, DiseaseRecordBean>(){
			@Override
			protected DiseaseRecordBean doInBackground(Integer... arg0) {
				// TODO Auto-generated method stub
				return DbOperator.getInstance(context).getDiseaseRecordHealthManagerById(arg0[0]);
			}
			
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				LoadingTip.showDialog(context, null);
			}
			
			@Override
			protected void onPostExecute(DiseaseRecordBean result) {
				// TODO Auto-generated method stub
				bean = result == null ? new DiseaseRecordBean() : result;
				content_txt[0]= bean.getHealthAna() == null ? "" : Html.fromHtml(bean.getHealthAna()).toString();
				content_txt[1]= bean.getHealthInstruct() == null ? "" : Html.fromHtml(bean.getHealthInstruct()).toString();
				content_txt[2]=bean.getHealthDirect() == null ? "" : Html.fromHtml(bean.getHealthDirect()).toString();
				initiaView(view);
				LoadingTip.hideDialog();
			}
			
		};
		task.execute(id);
		
		return view;
	}
	
	@Override
	protected void initiaView(View view) {
		// TODO Auto-generated method stub
		disease=(EditText) view.findViewById(R.id.disease);
		content=(EditText) view.findViewById(R.id.content);
		content.setText(content_txt[0]);
		
		searchBtn=(TextView) view.findViewById(R.id.searchBtn);
		searchBtn.setOnClickListener(click);
		
		remindTime=(TextView) view.findViewById(R.id.remind_time);
		remindTime.setOnClickListener(click);
		remindTime.setText(bean.getRemindTime());
		
		tag=0;
		healthAnaBtn=(TextView) view.findViewById(R.id.healthAnaBtn);
		healthAnaBtn.setOnClickListener(click);
		
		healthInstructBtn=(TextView) view.findViewById(R.id.healthInstruct);
		healthInstructBtn.setOnClickListener(click);
		
		healthDirectBtn=(TextView) view.findViewById(R.id.healthDirect);
		healthDirectBtn.setOnClickListener(click);
		
		saveBtn=(LinearLayout) view.findViewById(R.id.saveBtn);
		saveBtn.setOnClickListener(click);
		
		cancelBtn=(LinearLayout) view.findViewById(R.id.cancelBtn);
		cancelBtn.setOnClickListener(click);
	}
	
	private class Click implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v==searchBtn) {
				final String searchWord=disease.getText().toString().trim();
				
				LoadingTip.showDialog(context, "正在查找，请稍候...");
				new Thread() {
					public void run() {
						final List<String> names=DbOperator.getInstance(context).selectDiseaseName(searchWord);	
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								if (names.size()<=0) {
									DialogHelper.showConfirmDialog(context, "没有相关搜索结果，请更换搜索关键词再试试！");
								} else {
									DialogHelper.selectDialog(context, "请选择类型", names, new DialogSelectCallback() {	
											@Override
											public void onDialogSelected(int position) {
												// TODO Auto-generated method stub
												String name=names.get(position);
												disease.setText(name);
												/**
												String[] healths=DbOperator.getInstance(context).getHealths(name);
												content_txt[0]=healths[0];
												content_txt[1]=healths[1];
												content_txt[2]=healths[2];
												content.setText(content_txt[tag]);
												*/
												AsyncTask<String, Integer, String[]> task = new AsyncTask<String, Integer, String[]>(){
													@Override
													protected String[] doInBackground(String... arg0) {
														// TODO Auto-generated method stub
														return DbOperator.getInstance(context).getHealths(arg0[0]);
													}
													
													@Override
													protected void onPreExecute() {
														// TODO Auto-generated method stub
														LoadingTip.showDialog(context, null);
													}
													
													@Override
													protected void onPostExecute(String[] result) {
														// TODO Auto-generated method stub
														if (result != null) {
															content_txt[0]= result[0] == null ? "" : Html.fromHtml(result[0]).toString();
															content_txt[1]= result[1] == null ? "" : Html.fromHtml(result[1]).toString();
															content_txt[2]= result[2] == null ? "" : Html.fromHtml(result[2]).toString();
															content.setText(content_txt[tag]);
														}
														LoadingTip.hideDialog();
													}
												};
												task.execute(name);
											}
										});
								}
								LoadingTip.hideDialog();
							}
						});
					}
				}.start();
				
			} else if (v==remindTime) {
				new DateTimeButton(context, remindTime).dateTimePickerDialog();
			} else if (v==healthAnaBtn) {
				healthAnaBtn.setBackgroundResource(R.color.green);
				healthInstructBtn.setBackgroundResource(R.color.light_green);
				healthDirectBtn.setBackgroundResource(R.color.light_green);
				getContent(tag);
				tag=0;
				content.setText(content_txt[tag]);
			} else if (v==healthInstructBtn) {
				healthAnaBtn.setBackgroundResource(R.color.light_green);
				healthInstructBtn.setBackgroundResource(R.color.green);
				healthDirectBtn.setBackgroundResource(R.color.light_green);
				getContent(tag);
				tag=1;
				content.setText(content_txt[tag]);
			} else if (v==healthDirectBtn) {
				healthAnaBtn.setBackgroundResource(R.color.light_green);
				healthInstructBtn.setBackgroundResource(R.color.light_green);
				healthDirectBtn.setBackgroundResource(R.color.green);
				getContent(tag);
				tag=2;
				content.setText(content_txt[tag]);
			} else if (v==saveBtn) {
				ContentValues values=new ContentValues();
				String remindTime_txt=remindTime.getText().toString();
				values.put("_remind_time", remindTime_txt);
				
				getContent(tag);
				values.put("_health_ana", content_txt[0] == null ? "" : Html.fromHtml(content_txt[0]).toString());
				values.put("_health_instruct", content_txt[1] == null ? "" : Html.fromHtml(content_txt[1]).toString());
				values.put("_health_direct", content_txt[2] == null ? "" : Html.fromHtml(content_txt[2]).toString());
				String date=null;
				String time=null;
				int alarmId=9*ConstConfig.BASE_ID+bean.getId();
				if (remindTime_txt!=null && !"".equals(remindTime_txt)) {
					values.put("_alarm_id", alarmId);
				}
				
				if (bean.getCid() > 0) {
					//服务端id存在则将这条记录标记为已修改
					values.put("_operation", ConstConfig.OPERATION_MODIFY);
				}
				
				int row=DbOperator.getInstance(context).updateData(ConstConfig.DISEASE_RECORD_TABLE, values, id);
				if (row>0) {
					Toast.makeText(context, "保存成功！", Toast.LENGTH_SHORT).show();
					getActivity().getSupportFragmentManager().popBackStack();
					if (remindTime_txt!=null && !"".equals(remindTime_txt)) {
						String patientName=DbOperator.getInstance(context).getFieldById(ConstConfig.PATIENT_FILE_TABLE, bean.getPatientId(), "_name");
						String[] date_time=remindTime_txt.split("\\s");
						date=date_time[0];
						time=date_time[1];
						
						Date setDate = null;
						try {
							setDate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(remindTime_txt);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						Calendar calendar=Calendar.getInstance();
						Date systemDate=calendar.getTime();	
						if (!setDate.before(systemDate)) {
							String mobile=DbOperator.getInstance(context).getFieldById(ConstConfig.PATIENT_FILE_TABLE, bean.getPatientId(), "_mobile");
							String tip=DbOperator.getInstance(context).getFieldById(ConstConfig.DISEASE_RECORD_TABLE, bean.getId(), "_health_direct");
							if (mobile!=null && !"".equals(mobile.trim()) && tip!=null && !"".equals(tip.trim())) {	
								AlarmReceiver.setAlarm(getActivity(), date, time, alarmId, "给"+patientName+"发送健康提示短信！"+ConstConfig.IMAGE_SPLIT+
										mobile+ConstConfig.IMAGE_SPLIT+tip);
							} else {
								Toast.makeText(context, "手机号码或健康指示未设置！", Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(context, "发送短信时间不能早于现在！", Toast.LENGTH_SHORT).show();
						}
					}
				} else {
					Toast.makeText(context, "保存失败！", Toast.LENGTH_SHORT).show();
				}
				
			} else if (v==cancelBtn) {
				getActivity().getSupportFragmentManager().popBackStack();
			}
		}
	}
	
	
	/**
	 * 切换按钮保存文字信息
	 * @param tag
	 */
	private void getContent(int tag){
		String contentString=content.getText().toString().trim();
		
		switch (tag) {
		case 0:
			content_txt[0]=contentString;
			break;

		case 1:
			content_txt[1]=contentString;
			break;
			
		case 2:
			content_txt[2]=contentString;
		}
	}	
	
	
}
